package com.qishi.exampleOne.cglibProxy;

import com.qishi.exampleOne.PerformanceMonitor;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {

    private Enhancer enhancer = new Enhancer();

    public Object getProxy(Class clazz) {

        //设置需要创建的子类的类别
        enhancer.setSuperclass(clazz);

        enhancer.setCallback(this);

        //通过字节码技术动态创建子类实例
        return enhancer.create();
    }




    //拦截父类所有方法的调用
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        PerformanceMonitor.begin(obj.getClass().getName() + "." + method.getName());

        //通过代理类调用父类的方法
        Object result = methodProxy.invokeSuper(obj, args);


        PerformanceMonitor.end();
        return result;
    }
}
